//
//  MYUserAccountViewModel.swift
//  MYSinaWeico
//
//  Created by Magic Yu on 16/4/11.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

private let userInfoKey = "com.mySinaWeico.userInfoKey"

import UIKit

//非常多的界面都会找viewModel获取数据
//viewModel处理业务逻辑 网络请求 数据缓存

class MYUserAccountViewModel: NSObject {
    
    //单例对象
    static let sharedAccountViewModel: MYUserAccountViewModel = MYUserAccountViewModel()
    
    var userAccount: MYUserAccount?
    
    //添加一个计算的属性(只读属性)
    var userLogin: Bool {
    
        //1.UserAccount的token 如果不为空 && 用户token不过期 用户已经登录
        // 没有过期 -> 过期日期和当前日期比较 -> 过期日期大于当前日期
//        return userAccount?.access_token != nil
        if let u = userAccount where u.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
        return true
        }
        
        //将userAccount设置为nil
        userAccount = nil
        return false
    }
    
    //增加一个用户头像NSURL类型的属性
    var headImageURL: NSURL? {
    
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    
    //私有化构造函数
    private override init() {
        super.init()
        userAccount = self.loadUserInfo()
    }
    

    //使用授权码 请求accesstoken
    func loadAccessToken(code: String,finished: (isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        HMNetworkTools.sharedTools.request(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                print(error)
               finished(isSuccess: false)
                return
            }
            
            //程序走到这 就一定没有错误
            print("授权成功")
            
            //获取用户信息 在请求成功的回调中
            self.loadUserInfo(result!,finished: finished)
            
        }
        
    }
    
    private func loadUserInfo(tokenResult: AnyObject,finished: (isSuccess: Bool) -> ()) {
        
        //尝试将result转换为字典
        guard let dict = tokenResult as? [String: AnyObject] else {
            
            finished(isSuccess: false)
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]!
        let uid = dict["uid"]!
        //字典数组中不能添加nil 因为可选项可能是nil 所以字典不能添加可选项 所以要转token和uid换为必选项
        let parameters = ["access_token":token, "uid":uid]
        
        HMNetworkTools.sharedTools.request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                print(error)
                finished(isSuccess: false)
                return
            }
            
            print("获取用户信息成功")
            
            //将用户信息保存起来
            print(result)
            //将anyObject转换成字典类型
            guard var userInfoDict = result as? [String: AnyObject] else {
                
                finished(isSuccess: false)
                return
            }
            
            //合并字典
            for(k,v) in dict {
                userInfoDict[k] = v
            }
            print(userInfoDict)
            
            self.saveUserAccount(userInfoDict)
            //执行成功的回调
            finished(isSuccess: true)
            
        }
    }
    
}

//存储数据 获取数据
extension MYUserAccountViewModel {

    func saveUserAccount(userInfoDict: [String: AnyObject]) {
    
        //保存完整的字典信息  偏好设置中不能保存nil
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        //1.将字典信息转换为模型对象
        let account = MYUserAccount(dict: userInfoDict)
        //2.获取模型对象字典信息
        let keys = ["access_token","avatar_large","name","expires_in","uid"]
        let accountDict = account.dictionaryWithValuesForKeys(keys)
        //3.将对象的字典信息保存在偏好设置中
        userDefaults.setObject(accountDict, forKey: userInfoKey)
        //4.同步
        userDefaults.synchronize()
        
        print(NSHomeDirectory())
        
    }
    
    
    //获取沙盒中存储的数据
    func loadUserInfo() -> MYUserAccount? {
    
        //1.获取字典信息
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String: AnyObject] else {
        return nil
        }
        
        //2.将字典转为模型
        let account = MYUserAccount(dict: dict)
        return account
        
    }
    
    
}






